package com.google.code.opengw.server;

import java.security.cert.X509Certificate;
import java.util.HashMap;

import com.google.code.opengw.policy.PolicyUser;
import com.google.code.opengw.support.OpenGWException;
import com.google.code.opengw.support.OpenGWLogger;

public class DataStore {

	private static DataStore dataStore;

	private HashMap<String, PolicyUser> userTable;
	private HashMap<String, X509Certificate> certificateTable;

	static {
		dataStore = new DataStore();
	}

	private DataStore() {
		userTable = new HashMap<String, PolicyUser>();
		certificateTable = new HashMap<String, X509Certificate>();
	}

	public static DataStore getInstance() {
		return dataStore;
	}

	public void addTrustedCertificate(String key, X509Certificate certificate) {
		certificateTable.put(key, certificate);
	}

	public X509Certificate getTrustedCertificate(String key)
			throws OpenGWException {
		X509Certificate certificate = certificateTable.get(key);
		if (certificate != null)
			return certificate;

		throw new OpenGWException(
				OpenGWException.CERTIFICATE_NOT_FOUND_IN_TRUSTSTORE);
	}

	public void addPolicyUser(PolicyUser policyUser) throws OpenGWException {
		if (!userTable.containsKey(policyUser.getUsername())){
			userTable.put(policyUser.getUsername(), policyUser);
			OpenGWLogger.addInfo(this.getClass(), "User initialized : " + policyUser.toString());
		} else
			throw new OpenGWException(OpenGWException.format(
					OpenGWException.POLICY_USER_ALREADY_EXISTS,
					policyUser.getUsername()));
	}

	public PolicyUser getPolicyUser(String username) throws OpenGWException {
		PolicyUser policyUser = userTable.get(username);
		if (policyUser == null)
			throw new OpenGWException(OpenGWException.format(
					OpenGWException.POLICY_USER_NOT_FOUND, username));

		return policyUser;
	}

}
